package com.lzx.adx.report.controller.v1.ks;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.ElmCovertKsEventTypeEnums;
import com.lzx.adx.report.enums.EventTypeEnums;
import com.lzx.adx.report.model.huawei.request.HwUploadRequest;
import com.lzx.adx.report.model.ks.request.KsCallBackRequest;
import com.lzx.adx.report.model.ks.request.KsReportRequest;
import com.lzx.adx.report.service.AccountService;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.HwSecureUtil;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/dsp")
@RestController
@Slf4j
public class KsReportController {

    @Resource
    private ReportService reportService;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private AccountService accountService;



    @GetMapping("/v1/report")
    public ResponseEntity v1Reqport(KsReportRequest ksReportRequest, HttpServletRequest request){
        return report(ksReportRequest);
    }

    @GetMapping("/v2/report")
    public ResponseEntity v2Reqport(KsReportRequest ksReportRequest, HttpServletRequest request){
        return report(ksReportRequest);
    }

    @GetMapping("/v3/report")
    public ResponseEntity v3Reqport(KsReportRequest ksReportRequest, HttpServletRequest request){
        return report(ksReportRequest);
    }

    @GetMapping("/v4/report")
    public ResponseEntity v4Reqport(KsReportRequest ksReportRequest, HttpServletRequest request){
        return report(ksReportRequest);
    }

    @GetMapping("/v5/report")
    public ResponseEntity v5Reqport(KsReportRequest ksReportRequest, HttpServletRequest request){
        return report(ksReportRequest);
    }


    /**
     * 24广告位的
     * @param ksReportRequest
     * @param request
     * @return
     */
    @GetMapping("/v24/report")
    public ResponseEntity v24Reqport(KsReportRequest ksReportRequest, HttpServletRequest request){
        return report(ksReportRequest);
    }


    /**
     * 转换数据回传回调
     * @param requestId 请求事件ID
     * @param event_type 转换类型
     * @param event_time 转换时间
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/callback")
    public ResponseEntity v1callBackUrl(String requestId,String event_type,String event_time) throws Exception {
        return callback(requestId, event_type, event_time);
    }






    @NotNull
    private ResponseEntity<?> report(KsReportRequest ksReportRequest) {
        log.info("快手->饿了么上报请求的参数为{}", JSON.toJSONString(ksReportRequest));
        //广点通，转换
        ReportDTO reportDTO=reportMapper.toReportKsReportDTO(ksReportRequest);
        reportDTO.setBizRequestId(IdUtil.fastUUID());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JSON.toJSONString(ksReportRequest));
        reportExecutor.execute(()->{
            reportService.saveData(reportDTO);
        });

        //获取配置信息
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(ksReportRequest.getDspId());

        //2.1进行宏替换
        String resultUrl= UrlUtil.handKsjsMarcroReplace(accountDTO.getDspReportUrl(),reportDTO,accountDTO.getDspCallbackUrl());
        //2.2 在进行md5加盐出来
        String sign= SecureUtil.md5(resultUrl+accountDTO.getDspSalt());
        String finalUrl=UrlUtil.handElmSalt(resultUrl,sign);

        log.info("账户号{},【快手-饿了么】,完整的饿了么请求地址为{}",ksReportRequest.getDspId(),finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账户号{},【快手-饿了么】,接收快手极速上报的情况，响应的结果为{}",ksReportRequest.getDspId(),body);
        JSONObject jsonObject=JSONObject.parseObject(body);
        //响应状态码成功
        if(jsonObject.get("success").equals(true) && jsonObject.get("result").equals(true)){
            return ResponseEntity.ok(new Result());
        }else{
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }



    @NotNull
    public ResponseEntity<?> callback(String requestId, String event_type, String event_time) {
        log.info("接收了快手-饿了么回调信息，请求流水号{},回调类型为{}，回调时间{}", requestId, event_type, event_time);
        if(StringUtils.isBlank(event_time) || StringUtils.isBlank(event_type)){
            log.info("请求参数异常，event_type{},event_time{]", event_type, event_time);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //1.把转换结果更新到数据库
        Map<String,Object> params=new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if(CollectionUtil.isNotEmpty(list)){
            reportDTO = list.get(0);
            reportDTO.setResultType(event_type);
            reportDTO.setResultTime(event_time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,event_type);
        }else{
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }


        //2.回调渠道，调用快手回传接口
        Map<String,Object> reqParams=new HashMap<>();
        reqParams.put("event_type",ElmCovertKsEventTypeEnums.getKsCode(reportDTO.getResultType()));
        reqParams.put("event_time",reportDTO.getResultTime());
        //组装参数和url
        String urlParams = URLUtil.buildQuery(reqParams, StandardCharsets.UTF_8);
        String finalReqUrl=reportDTO.getCallback()+"&"+urlParams;
        log.info("账户号【{}】，进行快速回调的请求参数为{}",reportDTO.getDspId(),finalReqUrl);
        String result =  HttpUtil.createGet(finalReqUrl).execute().body();
        log.info("账户号【{}】，接收快手饿了么的转换响应的结果为-{}",reportDTO.getDspId(),result);
//        JSONObject jsonObject=JSONObject.parseObject(result);
//        Integer resultCode = jsonObject.getInteger("result");

        return ResponseEntity.ok(new Result());
    }


}
